var i = 0;
var totalHours = 0;
var debug = false;

function editDependencyRow(name){
    i = 0;

    //copy the values from the row you want to edit and put them in the textFields
    var nameVal = document.getElementById("nameField" + name).value;
    var commentsVal = document.getElementById("commentsField" + name).value;

    var dependencyDropdown = document.getElementById("dependencyDropdown");
    dependencyDropdown.value = nameVal;

    var commentsTextField = document.getElementById("commentsTextField");
    commentsTextField.value = commentsVal;

    //remove the row
    removeDependencyRow(name);
}

function removeDependencyRow(whichPressed) {
    i = 0;
    var table = document.getElementById('dependencyTable');
    var rowID = 'row' + whichPressed;
    if (debug) {
        console.log('row' + whichPressed);
        var rowCount = table.rows.length;
        console.log("Num Rows Before: " + rowCount);
    }
    //table.children[0].removeChild(row);
    var rowCount = table.rows.length;
    for (var i = 0; i < rowCount; i++) {
        if (table.rows[i].id === rowID) {
            table.deleteRow(i);
            break;
        }
    }
}

function addDependencyRow() {
    //get a reference to the table
    var table = document.getElementById('dependencyTable');
    var e = document.getElementById('dependencyDropdown');
    //default selection??
    if(isDefaultSelection(e)){
        e.style.background = 'Yellow';
        return;
    }
    else{
       e.style.background = 'White'; 
    }
    //duplicate selection??
    //to do
    i = 0;
    

    //insert a row at the end of the table <TR>
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    //insert each cell <TD>
    var subtask = row.insertCell(0);
    var comments = row.insertCell(1);
    var edit = row.insertCell(2);
    var remove = row.insertCell(3);
    //validate

    //set default nameField 
    var nameField = "nameField" + i;

    //keep incrementing until the id does not exist
    while (document.getElementById(nameField) !== null) {
        //console.log("i++");
        i++;
        nameField = "nameField" + i;
    }
    //set the names for each hidden field
    var nameField = "nameField" + i;
    var commentsField = "commentsField" + i;
    row.id = 'row' + i;
    //add the hidden fields and values to each TD
    
    var nameValue = e.options[e.selectedIndex].text;
    var hiddenNameField = "<input type=\"hidden\"  id=\"" + nameField + "\" name = \"" + nameField + "\" value=\"" + e.value + "\"/>";
    subtask.innerHTML = hiddenNameField + nameValue;

    var commentsValue = document.getElementById('commentsTextField').value;
    var hiddenRateField = "<input type=\"hidden\"  id=\"" + commentsField + "\" name = \"" + commentsField + "\" value=\"" + commentsValue + "\"/>";
    comments.innerHTML = hiddenRateField + commentsValue;

    edit.innerHTML = "<input type=\"button\" name = \"" + i + "\" value=\"Edit\" onclick=\"editDependencyRow(this.name)\">";
    remove.innerHTML = "<input type=\"button\" name = \"" + i + "\" value=\"Remove\" onclick=\"removeDependencyRow(this.name)\">";
    document.getElementById('commentsTextField').value = "";
    document.getElementById("dependencyDropdown").selectedIndex = 0;
}

function addEDRRow() {
    var table = document.getElementById('edrSubmitTable');

    //These are the elements we are going to insert
    var row = document.createElement('tr');
    var name = document.createElement('td');
    platform = document.getElementById('platformDropdown');
    sensor = document.getElementById('sensorDropdown');
    parameter = document.getElementById('parameterDropdown');
    limitation = document.getElementById('limitationTextField');
    relevance = document.getElementById('relevanceDropdown');

    if (isDefaultSelection(platform)) {
        document.getElementById("edrSubmitBox").innerHTML = "Invalid Platform Selection";
    }
    if (isDefaultSelection(sensor)) {
        document.getElementById("edrSubmitBox").innerHTML = "Invalid Sensor Selection";
    }
    if (isDefaultSelection(parameter)) {
        document.getElementById("edrSubmitBox").innerHTML = "Invalid Parameter Selection";
    }
    if (isDefaultSelection(relevance)) {
        document.getElementById("edrSubmitBox").innerHTML = "Invalid Relevance Selection";
    }

//    platformID = platform.value;
//    sensorID = sensor.value;
//    parameterID = parameter.value;
//    limit = limitation.value
//    relevanceID = relevance.value;

    row.innerHTML = "<td>" + platform.text + "</td>"
//    name.innerHTML = nameSelected;
//    var nameField = "agency" + i;
//
//    while (document.getElementById(nameField) !== null) {
//        //console.log("i++");
//        i++;
//        nameField = "agency" + i;
//    }
//    var nameTd = "<td> " + name.innerHTML + "</td>";
//    //var removeButton = "<td><input type=\"button\" name = \"" + i + "\" value=\"Remove\" onclick=\"removeAgencyRow(this.name)\"></td>";
//    var hiddenField = "<input type=\"hidden\"  id=\"" + nameField + "\" name = \"" + nameField + "\" value=\"" + valueSelected + "\"/>";
//    row.id = "row" + i;
//    if (debug) {
//        console.log('row' + i+ 'added');
//    }
//    //row.innerHTML = nameTd + removeButton + hiddenField;
//    row.innerHTML = nameTd + hiddenField;
    table.appendChild(row);
//    i++;
}

function isDefaultSelection(element) {
    selectedValue = element.options[element.selectedIndex].innerHTML;
    //document.getElementById("edrSubmitBox").innerHTML=selectedValue;
    if ("defaultSelection" === selectedValue || "(Select)" === selectedValue) {
        return true;
    }
    else {
        return false;
    }
}

function addAgencyRow() {
    //i = 0;
    var table = document.getElementById('agencyTable');

    //These are the elements we are going to insert
    var row = document.createElement('tr');
    var name = document.createElement('td');
    valueSelected = document.getElementById('agencyDropdown').value;
    temp = document.getElementById('agencyDropdown');
    nameSelected = temp.options[temp.selectedIndex].innerHTML;
    if ("defaultSelection" === nameSelected) {
        return;
    }
    name.innerHTML = nameSelected;
    var nameField = "agency" + i;

    while (document.getElementById(nameField) !== null) {
        //console.log("i++");
        i++;
        nameField = "agency" + i;
    }
    var nameTd = "<td> " + name.innerHTML + "</td>";
    //var removeButton = "<td><input type=\"button\" name = \"" + i + "\" value=\"Remove\" onclick=\"removeAgencyRow(this.name)\"></td>";
    var hiddenField = "<input type=\"hidden\"  id=\"" + nameField + "\" name = \"" + nameField + "\" value=\"" + valueSelected + "\"/>";
    row.id = "row" + i;
    if (debug) {
        console.log('row' + i + 'added');
    }
    //row.innerHTML = nameTd + removeButton + hiddenField;
    row.innerHTML = nameTd + hiddenField;
    table.appendChild(row);
    i++;
}

function removeAgencyRow(whichPressed) {
    i = 0;
    var table = document.getElementById('agencyTable');
    var row = document.getElementById('row' + whichPressed);
    if (debug) {
        console.log('row' + whichPressed);
        console.log(table.childElementCount);
        console.log('ROW: ' + row.id);
    }
    table.children[0].removeChild(row);
}

function addPerformerRow() {
    i = 0;
    //get a reference to the table
    var table = document.getElementById('performerTable');

    //insert a row at the end of the table <TR>
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    //insert each cell <TD>
    var name = row.insertCell(0);
    var hours = row.insertCell(1);
    var rate = row.insertCell(2);
    var cost = row.insertCell(3);
    var edit = row.insertCell(4);
    var remove = row.insertCell(5);

    //validate the form
    reason = validatePerformerAdd();
    if (reason !== "") {
        alert("Some fields need correction:\n" + reason);
        return false;
    }
    else {
        //set default nameField
        var nameField = "nameField" + i;

        //keep incrementing until the id does not exist
        while (document.getElementById(nameField) !== null) {
            //console.log("i++");
            i++;
            nameField = "nameField" + i;
        }
        //set the names for each hidden field
        var nameField = "nameField" + i;
        var hourField = "hourField" + i;
        var rateField = "rateField" + i;
        row.id = 'row' + i;
        //add the hidden fields and values to each TD
        var nameValue = document.getElementById('performerName').value;
        var hiddenNameField = "<input type=\"hidden\"  id=\"" + nameField + "\" name = \"" + nameField + "\" value=\"" + nameValue + "\"/>";
        name.innerHTML = hiddenNameField + nameValue;

        var rateValue = document.getElementById('performerRate').value;
        var hiddenRateField = "<input type=\"hidden\"  id=\"" + rateField + "\" name = \"" + rateField + "\" value=\"" + rateValue + "\"/>";
        rate.innerHTML = hiddenRateField + rateValue;

        var hourValue = document.getElementById('performerHours').value;
        var hiddenhourField = "<input type=\"hidden\"  id=\"" + hourField + "\" name = \"" + hourField + "\" value=\"" + hourValue + "\"/>";
        hours.innerHTML = hiddenhourField + hourValue;

        cost.innerHTML = document.getElementById('performerHours').value * document.getElementById('performerRate').value;

        // var editButton = "<td><input type=\"button\" name = \"" + i + "\" value=\"Edit\" onclick=\"editPerformerRow(this.name)\"></td>";
        // var removeButton = "<td><input type=\"button\" name = \"" + i + "\" value=\"Remove\" onclick=\"removePerformerRow(this.name)\"></td>";

        edit.innerHTML = "<input type=\"button\" name = \"" + i + "\" value=\"Edit\" onclick=\"editPerformerRow(this.name)\">";
        remove.innerHTML = "<input type=\"button\" name = \"" + i + "\" value=\"Remove\" onclick=\"removePerformerRow(this.name)\">";

        i++;
        if (debug) {
//            console.log("total: " + totalHours);
//            console.log(nameTd);
//            console.log(hoursTd);
//            console.log(rateTd);
//            console.log(costTd);
//            console.log("rowId: " + row.id);
//            console.log("performer added " + row.innerHTML);
            //console.log(row.outerHTML);
        }
        document.getElementById("performerName").value = "";
        document.getElementById("performerHours").value = "";
        document.getElementById("performerRate").value = "";
    }
}

function editPerformerRow(name) {
    i = 0;

    //copy the values from the row you want to edit and put them in the textFields
    var nameVal = document.getElementById("nameField" + name).value;
    var hoursVal = document.getElementById("hourField" + name).value;
    var rateVal = document.getElementById("rateField" + name).value;

    var nameTextfield = document.getElementById("performerName");
    nameTextfield.value = nameVal;

    var hourTextfield = document.getElementById("performerHours");
    hourTextfield.value = hoursVal;

    var rateTextfield = document.getElementById("performerRate");
    rateTextfield.value = rateVal;

    //remove the row
    removePerformerRow(name);

}

function removePerformerRow(whichPressed) {
    i = 0;
    var table = document.getElementById('performerTable');
    var row = document.getElementById('row' + whichPressed);
    var rowID = 'row' + whichPressed;
    if (debug) {
        console.log('row' + whichPressed);
        var rowCount = table.rows.length;
        console.log("Num Rows Before: " + rowCount);
    }
    //table.children[0].removeChild(row);
    var rowCount = table.rows.length;
    for (var i = 0; i < rowCount; i++) {
        if (table.rows[i].id === rowID) {
            table.deleteRow(i);
            break;
        }
    }
}

function addAiRow() {
    //get a reference to the table
    var table = document.getElementById('aiTable');

    //These are the elements we are going to insert
    var row = document.createElement('tr');
    var name = document.createElement('td');
    var phone = document.createElement('td');
    var email = document.createElement('td');

    if (document.getElementById('aiName').value.length === 0 || document.getElementById('aiPhone').value.length === 0 || document.getElementById('aiEmail').value.length === 0) {
        return;
    }
    //set their values according to what was input into the text Fields
    name.innerHTML = document.getElementById('aiName').value;
    phone.innerHTML = document.getElementById('aiPhone').value;
    email.innerHTML = document.getElementById('aiEmail').value;

    var nameField = "nameField" + i;
    //console.log("i: " + i + " name: " + nameField + " value: " + document.getElementById(nameField))
    //we do this because the user may have removed a row and the indices may be out of order
    while (document.getElementById(nameField) !== null) {
        //console.log("i++");
        i++;
        nameField = "nameField" + i;
    }
    var nameField = "nameField" + i;
    var phoneField = "phoneField" + i;
    var emailField = "emailField" + i;
//    var nameTd = "<td class=\"blackFont\"> <input type=\"hidden\"  id = \"" + nameField + "\" name = \"" + nameField + "\" value=\"" + name.innerHTML + "\">" + name.innerHTML + "</td>";
//    var phoneTd = "<td class=\"blackFont\"> <input type=\"hidden\"  id = \"" + phoneField + "\" name = \"" + phoneField + "\" value=\"" + phone.innerHTML + "\">" + phone.innerHTML + "</td>";
//    var emailTd = "<td class=\"blackFont\"> <input type=\"hidden\"  id= \"" + emailField + "\" name = \"" + emailField + "\" value=\"" + email.innerHTML + "\">" + email.innerHTML + "</td>";
    
    var nameTd = document.createElement('td');
    nameTd.innerHTML = "<input type=\"hidden\"  id = \"" + nameField + "\" name = \"" + nameField + "\" value=\"" + name.innerHTML + "\">" + name.innerHTML;
    nameTd.className = "blackFont";
    row.appendChild(nameTd);
    var phoneTd = document.createElement('td');
    phoneTd.innerHTML = "<input type=\"hidden\"  id = \"" + phoneField + "\" name = \"" + phoneField + "\" value=\"" + phone.innerHTML + "\">" + phone.innerHTML;
    row.appendChild(phoneTd);
    var emailTd = document.createElement('td');
    emailTd.innerHTML = "<input type=\"hidden\"  id= \"" + emailField + "\" name = \"" + emailField + "\" value=\"" + email.innerHTML + "\">" + email.innerHTML;
    row.appendChild(emailTd);
    row.className = "field";
    //var tdText = nameTd + phoneTd + emailTd + "<td></td>"
    //row.innerHTML = tdText;
    //console.log(row.innerHTML);
    if (debug) {
        console.log(row.innerHTML);
    }
    ///row.appendChild(test);
    //row.appendChild(hours);
    //row.appendChild(rate);
    //row.appendChild(cost);
    //append to the table
    table.children[0].appendChild(row);
    //clear the textfields
    document.getElementById('aiName').value = "";
    document.getElementById('aiPhone').value = "";
    document.getElementById('aiEmail').value = "";
    i++;
}

function removeAiRow(whichPressed) {
    var table = document.getElementById('aiTable');
    var row = document.getElementById('row' + whichPressed);
    if (debug) {
        console.log(table.childElementCount);
    }
    table.children[0].removeChild(row);
    //table.children[0].deleteRow(whichPressed);
}

function validatePerformerAdd() {
    var reason = "";

    duration = document.getElementById('durationTextfield').value;
    name = document.getElementById('performerName').value;
    hours = document.getElementById('performerHours').value;
    rate = document.getElementById('performerRate').value;

    reason += validateEmpty(document.getElementById('performerName'));
    reason += validateEmpty(document.getElementById('performerHours'));
    reason += validateEmpty(document.getElementById('performerRate'));
    if (reason !== "") {
        return reason;
    }

    if (isNaN(hours)) {
        reason += "Hours field must be a number.\n";
        document.getElementById('performerHours').style.background = 'Yellow';
    }
    else {
        document.getElementById('performerHours').style.background = 'White';
    }
    if (isNaN(rate)) {
        reason += "Rate field must be a number.\n";
        document.getElementById('performerRate').style.background = 'Yellow';
    }
    else {
        document.getElementById('performerRate').style.background = 'White';
    }
    if (isNaN(duration)) {
        reason += "Duration field must be a number.\n";
        document.getElementById('durationTextfield').style.background = 'Yellow';
    }
    else {
        document.getElementById('durationTextfield').style.background = 'White';
    }
    if (parseInt(duration) < parseInt(hours)) {
        reason += "Hours cannot be greater that duration of the task.\n";
        document.getElementById('performerHours').style.background = 'Yellow';
    }
    else {
        document.getElementById('performerHours').style.background = 'White';
    }

    if (parseInt(duration) < (parseInt(totalHours) + parseInt(hours))) {
        reason += "Total Hours cannot be greater that duration of the task.\n";
        document.getElementById('durationTextfield').style.background = 'Yellow';
    }
    else {
        document.getElementById('durationTextfield').style.background = 'White';
    }
    return reason;
}

function validateEmpty(fld) {
    var output = "";
    if (fld.value.length === 0) {
        fld.style.background = 'Yellow';
        output = fld.name + " is blank \n";
    } else {
        fld.style.background = 'White';
    }
    return output;
}


